const Usecase = require('../../shared/usecase/Usecase')
const { OldPasswordNotMatchError } = require('../../domain/auth/error')
class ModifyPassword extends Usecase {
  constructor({ userRepo, database }) {
    super()
    this.userRepo = userRepo
    this.sequelize = database.sequelize
  }

  async execute(data, currentUser) {
    const match = await currentUser.comparePassword(data.oldPassword)
    if (!match) throw new OldPasswordNotMatchError()
    currentUser.password = data.newPassword
    await currentUser.validate()
    await currentUser.bcryptPassword()
    const transaction = await this.sequelize.transaction()
    try {
      await this.userRepo.update(
        currentUser,
        {
          transaction,
        },
        false
      )
      await transaction.commit()
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  }
}

module.exports = ModifyPassword
